<template>
    <!-- 顶部导航栏 -->
    <div class="soubg">
      <div class="sou container">
        <!-- 所在收货地区 -->
        <span class="s_city_b">
          <span class="fl">送货至：</span>
          <CitySelector v-model="selectedCity" @change="onCityChange" />
        </span>
        
        <span class="fr">
          <span class="fl" v-if="!isLoggedIn">
            你好，请<router-link to="/login">登录</router-link>&nbsp; 
            <router-link to="/register" class="text-primary">免费注册</router-link>&nbsp;|&nbsp;
            <router-link to="/orders">我的订单</router-link>&nbsp;|
          </span>
          <span class="fl" v-else>
            你好，<router-link to="/user"> {{ username }} </router-link> &nbsp;|&nbsp;
            <router-link to="/orders">我的订单</router-link>&nbsp;|&nbsp;
            <span v-if="userType === 1">
              <router-link to="/user">管理中心</router-link>&nbsp;|&nbsp;
            </span>
            <span>
              <a href="#" @click.prevent="handleLogout">退出</a>
            </span>
          </span>
          
          <span class="ss">
            <div class="ss_list">
              <router-link to="/favorites">收藏夹</router-link>
              <div class="ss_list_bg">
                <div class="s_city_t"></div>
                <div class="ss_list_c">
                  <ul>
                    <li><router-link to="/favorites">我的收藏夹</router-link></li>
                    <li><router-link to="/favorites/products">商品收藏</router-link></li>
                  </ul>
                </div>
              </div>     
            </div>
            
            <div class="ss_list">
              <a href="#">客户服务</a>
              <div class="ss_list_bg">
                <div class="s_city_t"></div>
                <div class="ss_list_c">
                  <ul>
                    <li><router-link to="/help">帮助中心</router-link></li>
                    <li><router-link to="/contact">联系客服</router-link></li>
                    <li><router-link to="/feedback">意见反馈</router-link></li>
                  </ul>
                </div>
              </div>    
            </div>
            
            <div class="ss_list">
              <a href="#">网站导航</a>
              <div class="ss_list_bg">
                <div class="s_city_t"></div>
                <div class="ss_list_c">
                  <ul>
                    <li><router-link to="/category">商品分类</router-link></li>
                    <li><router-link to="/brands">品牌大全</router-link></li>
                  </ul>
                </div>
              </div>    
            </div>
          </span>
          
          <span class="fl">|&nbsp;关注我们：</span>
          <span class="s_sh">
            <a href="#" class="sh1">新浪</a>
            <a href="#" class="sh2">微信</a>
          </span>
          <span class="fr">
            |&nbsp;<a href="#">手机版&nbsp;<img src="@/assets/images/s_tel.png" align="absmiddle" /></a>
          </span>
        </span>
      </div>
    </div>
    
    <!-- 主头部区域 -->
    <div class="top container">
      <div class="logo">
        <router-link to="/">
          <img src="@/assets/images/logo.png" alt="EasyBuy" />
        </router-link>
      </div>
      
      <div class="search">
        <form @submit.prevent="handleSearch">
          <input 
            type="text" 
            v-model="keywords" 
            placeholder="请输入搜索关键字"
            class="s_ipt" 
          />
          <input type="submit" value="搜索" class="s_btn" />
        </form>                      
        <span class="fl">
          <a href="#" @click="searchFor('咖啡')">咖啡</a>
          <a href="#" @click="searchFor('iphone 6S')">iphone 6S</a>
          <a href="#" @click="searchFor('新鲜美食')">新鲜美食</a>
          <a href="#" @click="searchFor('蛋糕')">蛋糕</a>
          <a href="#" @click="searchFor('日用品')">日用品</a>
          <a href="#" @click="searchFor('连衣裙')">连衣裙</a>
        </span>
      </div>
      
      <ShoppingCart :is-logged-in="isLoggedIn" @cart-updated="onCartUpdated" />
    </div>
</template>

<script>
import CitySelector from './CitySelector.vue'
import ShoppingCart from './ShoppingCart.vue'

export default {
  name: 'AppHeader',
  components: {
    CitySelector,
    ShoppingCart
  },
  props: {
    isLoggedIn: {
      type: Boolean,
      default: false
    },
    username: {
      type: String,
      default: ''
    },
    userType: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      selectedCity: '四川',
      keywords: '',
      isSearchVisible: false
      // 移除isLoggedIn和username，避免与props冲突
    }
  },
  watch: {
    // 监听props中的isLoggedIn变化
    isLoggedIn: {
      handler(newVal) {
        // 不需要在这里更新data，直接使用props
      },
      immediate: true
    },
    // 监听props中的username变化
    username: {
      handler(newVal) {
        // 不需要在这里更新data，直接使用props
      },
      immediate: true
    }
  },
  mounted() {
    // 页面加载时检查登录状态
    this.checkLoginStatus()
  },
  methods: {
    checkLoginStatus() {
      // 从本地存储获取用户信息
      const userInfo = localStorage.getItem('userInfo')
      if (userInfo) {
        try {
          const user = JSON.parse(userInfo)
          // 不应该直接修改props，应该通过事件通知父组件更新
          // 这里只是检查本地存储状态，实际显示由父组件传递的props决定
        } catch (e) {
          console.error('解析用户信息失败:', e)
          // 如果解析失败，清除无效的用户信息
          localStorage.removeItem('userInfo')
        }
      }
    },
    onCityChange(city) {
      this.selectedCity = city
      this.$emit('city-change', city)
    },
    handleSearch() {
      if (this.keywords.trim()) {
        this.$router.push({
          name: 'SearchResults',
          query: { keyword: this.keywords }
        })
      }
    },
    searchFor(keyword) {
      this.keywords = keyword
      this.handleSearch()
    },
    handleLogout() {
      this.$confirm('确定要退出登录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 清除本地存储的用户信息
        localStorage.removeItem('userInfo')
        localStorage.removeItem('token')
        
        // 通过事件通知父组件更新状态，而不是直接修改props
        this.$emit('logout')
        
        // 显示退出成功消息
        this.$message({
          message: '退出登录成功',
          type: 'success'
        })
        
        // 跳转到首页
        this.$router.push('/')
      }).catch(() => {
        // 用户取消退出
        this.$message({
          message: '已取消退出',
          type: 'info'
        })
      })
    },
    onCartUpdated(cartItems) {
      this.$emit('cart-updated', cartItems)
    }
  }
}
</script>

<style scoped>

</style>